﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

namespace Alogient.Cameleon.Sdk
{
    /// <summary>
    /// String functions, encoding, rewriting
    /// </summary>
    public class StringTools
    {
        private StringTools()
        {
        }


        #region HTML Encode, Remove unuseful tags
        


        /// <summary>
        /// Remove unuseful tags
        /// </summary>
        /// <param name="string_in">String to process</param>
        /// <returns>Input string without unuseful paragraph tags and spaces</returns>
        public static string RemoveUnusefulTags(string string_in)
        {
            if (string_in == null)
            {
                return null;
            }

            string string_out = string_in;
            // remove <p> at start if corresponding </p> is found at the end
            Regex Rx1 = new Regex("^<p[^>]*>", RegexOptions.IgnoreCase);
            Regex Rx2 = new Regex("</p>$", RegexOptions.IgnoreCase);
            // if the string starts with <p> and ends with </p>, remove the p tag
            // repeat this action until there is no more p tags
            Regex Rx = new Regex("<p[^>]*>[^<]*<\\/p>", RegexOptions.IgnoreCase);
            Regex rx_sp = new Regex("<p[^>]*>", RegexOptions.IgnoreCase);
            Regex rx_ep = new Regex("</p>", RegexOptions.IgnoreCase);
            bool stop_search = false;
            while (!stop_search && Rx1.IsMatch(string_out) && Rx2.IsMatch(string_out))
            {
                string temp_string_out = Rx2.Replace(Rx1.Replace(string_out, string.Empty), string.Empty);
                // counting ending tags </p>, stops if an end tag has not a corresponding start tag
                // remove pairs <p> </p>
                while (Rx.IsMatch(temp_string_out))
                    temp_string_out = rx_ep.Replace(rx_sp.Replace(temp_string_out, string.Empty), string.Empty);
                // if there are more </p> tags, stop
                // if not remove <p> at start and </p> at the end
                if (rx_ep.IsMatch(temp_string_out))
                    stop_search = true;
                else
                    string_out = Rx2.Replace(Rx1.Replace(string_out, string.Empty), string.Empty);
            }
            // remove <p>&nbsp;</p> at the end
            Rx = new Regex("<p[^>]*>&nbsp;<\\/p>$", RegexOptions.IgnoreCase);
            while (Rx.IsMatch(string_out))
                string_out = Rx.Replace(string_out, string.Empty);
            // remove all if the string contains only non-breaking spaces
            Rx = new Regex("^(&nbsp;)+$", RegexOptions.IgnoreCase);
            string_out = Rx.Replace(string_out, string.Empty);

            return string_out;
        }

        #endregion

        #region Encode

        /// <summary>
        /// Encode file name
        /// </summary>
        /// <param name="fileName">Filename to encode</param>
        /// <returns>Encoded filename</returns>
        public static string FileNameEncode(string fileName)
        {
            if (fileName.LastIndexOf(".") == -1)
            {
                return Encode(fileName);
            }
            
            string ext = fileName.Substring(fileName.LastIndexOf(".") + 1);
            string name = fileName.Replace("." + ext, string.Empty);
            return String.Format("{0}.{1}", Encode(name), ext);
        }

        /// <summary>
        /// Encode string
        /// </summary>
        /// <param name="str_in">String to encode</param>
        /// <returns>Input string encoded</returns>
        public static string Encode(string str_in)
        {
            if (str_in == null)
            {
                return string.Empty;
            }

            return System.Text.Encoding.ASCII.GetString(System.Text.Encoding.GetEncoding(1251).GetBytes(str_in));
        }

        /// <summary>
        /// Encode character
        /// </summary>
        /// <param name="char_in">Character to encode</param>
        /// <returns>Encoded character</returns>
        public static string EncodeChar(char char_in)
        {
            return System.Text.Encoding.ASCII.GetString(System.Text.Encoding.GetEncoding(1251).GetBytes(char_in.ToString()));
        }

        #endregion

        #region Url Rewriting

        /// <summary>
        /// Get current rewrite url
        /// </summary>
        /// <returns></returns>
        public static string GetRewriteUrl()
        {
            return GetRewriteUrl(HttpContext.Current.Request.Url.PathAndQuery);
        }

        /// <summary>
        /// Get rewrite url
        /// </summary>
        /// <param name="url">Url to rewrite</param>
        /// <returns>Rewrited url</returns>
        public static string GetRewriteUrl(string url)
        {
            string new_url = Regex.Replace(url, @"/[^/]+\.aspx\?", String.Format("/{0}?", HttpContext.Current.Request["__page"]));
            return Regex.Replace(new_url, @"&__page=[^&]+", string.Empty);
        }

        #endregion

        /// <summary>
        /// Build SQL query from string
        /// </summary>
        /// <param name="str">Search string</param>
        /// <returns>SQL formatted search query</returns>
        public static string QueryFromSearchString(string str)
        {
            if (str == null || str == string.Empty)
                return null;
            str = Regex.Replace(str, @"[^\w\.@-]", "%");
            str = Regex.Replace(str, @"\s+", " ").Trim();
            
            return String.Format(" #column# LIKE '%{0}%' ", str);
        }
    }
}
